// JavaScript Document

(function($){ 
	jQuery.fn.extend({  
		numberspinner: function(options) {
			
			var EVENT_TYPE_INPUT_CHANGED = "app.spinner.changed";
			
			var defaultOptions = {
				name: "",
				value: 1,
				onValueChanged: jQuery.noop()
			};
			
			return this.each(function() {
				var opt = $.extend(defaultOptions, options);
				var $container = jQuery(this),
				$lower = jQuery("<a class='lower_book_q' />"),
				$input = jQuery("<input type='text' id='" + opt.name + $container.attr("id") +"' name='" + opt.name  + "' maxlength='4' />").val(opt.value),
				$add = jQuery("<a class='add_book_q' />");
				
				$container.append($lower).append($input).append($add);
				
				$container.bind(EVENT_TYPE_INPUT_CHANGED, function(event, val) {
					var waresId = $container.attr("id");;
					opt.onValueChanged ? opt.onValueChanged(waresId, $input.val()) : jQuery.noop();
				});
				$lower.bind('click', value_down);
				$add.bind('click', value_up);
				$input.bind('change', function(event) {
					var val = parseInt($(this).val(), 10);
					if(isNaN(val)){
						val = 0;
					} if(val > 9999) {
						val = 9999;
					} else if(val < 0) {
						val = 0;
					}
					$(this).val(val);
					$container.trigger(EVENT_TYPE_INPUT_CHANGED, val);
				});
				
				function value_up() {
					var val = $input.val();
					val = Number(val) + Number(1);
					if(val > 9999) 
						val = 9999;
					if(val <  1)
						val = 1;  
					$input.val(val); 
					$container.trigger(EVENT_TYPE_INPUT_CHANGED, val);
				}
				
				function value_down() {
					var val = $input.val();
					val = Number(val) - Number(1);
					if(val > 9999) 
						val=9999;
					if(val < 0)
						val = 0;  
					$input.val(val);
					$container.trigger(EVENT_TYPE_INPUT_CHANGED, val);
				}
				
			});
			
        } 
    }); 
})(jQuery);